package org.visionlibrary.image.filters.thresholding;

import java.awt.Point;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.model.WindowFilter;


public class AdaptiveThreshold extends WindowFilter {
	protected int meanOffset = 10;

	protected int width;
	protected int height;

	public AdaptiveThreshold(int width, int height) {
		this.width = width;
		this.height = height;
	}

	public AdaptiveThreshold(int size) {
		this(size, size);
	}

	public AdaptiveThreshold() {
		this(3);
	}

	protected int getNewPixelVal(TiledImage src, Point p, int channel) {
		int value = 0;
		int count = 0;

		Point pIter = new Point();
		for (pIter.y = 0; pIter.y < windowHeight; pIter.y++)
			for (pIter.x = 0; pIter.x < windowWidth; pIter.x++) {
				int val = getWindowPixelVal(src, pIter, channel);
				value += val;
				count++;
			}

		int mean = value / count;
		int currentPixelVal = getWindowPixelVal(src, dstPointInWindow, channel);

		if (mean - currentPixelVal < meanOffset)
			return 0;
		else
			return 255;
	}

	protected void setWindowProperties() {
		windowWidth = width;
		windowHeight = height;
		dstPointInWindow = new Point(width / 2, height / 2);
	}

	public int getMeanOffset() {
		return meanOffset;
	}

	public void setMeanOffset(int meanOffset) {
		this.meanOffset = meanOffset;
	}
}
